package com.geek.framework.study.config.microprofile.converter;


import com.geek.framework.study.util.ServiceLoaderUtils;
import org.eclipse.microprofile.config.spi.Converter;

import java.util.List;

/**
 * 功能:
 * 1. 是否支持解析
 * 2. 传入要转化的类型; 返回转行后的类型
 */
public class StringConversionService {

    static StringConversionService sharedInstance;


    public static StringConversionService getSharedInstance() {
        StringConversionService scs = sharedInstance;
        if (sharedInstance == null) {
            synchronized (StringConversionService.class) {
                scs = sharedInstance;
                if (sharedInstance == null) {
                    scs = new StringConversionService();
                    sharedInstance = scs;
                }
            }
        }
        return scs;
    }

    private final Converters converters = new Converters();

    public StringConversionService() {
        addDiscoveredConverters();
    }


    public <T> boolean canConvert(String source, Class<T> tClass) {
        Converter converter = converters.matchConverter(source, tClass);
        return converter != null;
    }


    public <T> T convert(String source, Class<T> tClass) {
        Converter converter = converters.matchConverter(source, tClass);
        return (T) converter.convert(source);
    }

    public void addConverter(Converter... converters) {
        this.converters.addConverters(converters);
    }



    private void addDiscoveredConverters() {
        List<Converter> converters = ServiceLoaderUtils.loadSPI(Converter.class);
        for (Converter converter : converters) {
            addConverter(converter);
        }
    }


}
